<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>寻路算法</title>
    <style>
      .cell {
        width: 6px;
        height: 6px;
        background-color: gray;
        border-right: 1px solid #fff;
        border-bottom: 1px solid #fff;
        vertical-align: middle;
        display: inline-block;
      }
      .active {
        background-color: #000;
      }
      .container {
        width: 700px;
        /* font-size: 0; */
        line-height: 6px;
      }
    </style>
  </head>
  <body>
    <div class="container"></div>
    <button id="save">保存</button>
    <script>
      // 创建map数组
      let map = localStorage.getItem("map")
        ? JSON.parse(localStorage.getItem("map"))
        : Array(10000).fill(0);
      // 创建dom结构
      const container = document.getElementsByClassName("container")[0];
      const fg = document.createDocumentFragment();
      for (let y = 0; y < 100; y++) {
        for (let x = 0; x < 100; x++) {
          const cell = document.createElement("div");
          cell.classList.add("cell");
          cell.dataset.map = [x, y].join();
          if (map[y * 100 + x] === 1) {
            cell.classList.add("active");
          }
          fg.appendChild(cell);
        }
      }
      container.appendChild(fg);
      // 事件处理
      let isMouseDown = false;
      let isClear = false;
      document.addEventListener(
        "mousedown",
        (e) => {
          isMouseDown = true;
          isClear = e.which === 3;
        },
        false
      );
      document.addEventListener(
        "mouseup",
        (e) => {
          isMouseDown = false;
          isClear = false;
        },
        false
      );
      document.addEventListener(
        "mousemove",
        (e) => {
          const target = e.target;
          if (
            target.className.indexOf("cell") < 0 ||
            !(isMouseDown || isClear)
          ) {
            return false;
          }
          const [x, y] = target.dataset.map
            .split(",")
            .map((item) => Number(item));
          if (isMouseDown) {
            target.classList.add("active");
            map[y * 100 + x] = 1;
          }
          if (isClear) {
            target.classList.remove("active");
            map[y * 100 + x] = 0;
          }
        },
        false
      );
      document.addEventListener("contextmenu", (e) => e.preventDefault());

      // 保存
      document.getElementById("save").addEventListener("click", () => {
        localStorage.setItem("map", JSON.stringify(map));
      });
    </script>
  </body>
</html>
